import React, { useEffect, useState } from 'react'
import GLOBAL_CESIUM from '@/components/cesium/globalCesiumData'
import { useDispatch, useSelector } from 'react-redux'
import TaskFly from './taskFly'
import ControlFly from './controFly/ControlFly'

const MapAction = () => {
  let [taskObj, setTaskObj] = useState(null)
  const [showControl, setShowControl] = useState(false)
  const [controlKey, setControlKey] = useState(0)
  const viewer = GLOBAL_CESIUM.viewer

  const globalMapFun = useSelector((state) => state.mapFun.mapFun)

  useEffect(() => {
    globalMapAction(globalMapFun)
  }, [globalMapFun])

  const globalMapAction = (data) => {
    switch (data.type) {
      case 'fly':
        data.status === 1 ? wrjFly(data.data) : destroyWrjFly()
        break

      default:
        break
    }
  }

  const wrjFly = (data) => {
    destroyWrjFly()
    setShowControl(true)
    setTaskObj(new TaskFly(viewer, data.line, data.view))
  }

  const destroyWrjFly = () => {
    setShowControl(false)
    setControlKey((prev) => prev + 1) // 每次销毁强制更新 ControlFly
    if (taskObj) {
      taskObj.clear()
    }
    setTaskObj(null)
  }

  const changeView = () => {
    if (taskObj) {
      taskObj.changeView()
    }
  }

  const setPlayPause = () => {
    if (taskObj) {
      taskObj.playPause()
    }
  }

  return (
    <>
      {showControl ? (
        <ControlFly
          key={controlKey}
          changeView={changeView}
          setPlayPause={setPlayPause}
        />
      ) : null}
    </>
  )
}

export default MapAction
